package org.dromara.signIn.controller;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.stream.Collectors;

import cn.dev33.satoken.annotation.SaCheckLogin;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.signIn.domain.SignInTask;
import org.dromara.signIn.service.ISignInRecordService;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.signIn.domain.vo.SignInTaskVo;
import org.dromara.signIn.domain.bo.SignInTaskBo;
import org.dromara.signIn.service.ISignInTaskService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 任务
 *
 * @author KaijiaZhu
 * @date 2025-09-28
 */
@Validated
@RestController
@RequestMapping("/signIn/task")
public class SignInTaskController extends BaseController {

    private final ISignInTaskService signInTaskService;
    private final ISysUserService sysUserService;
    private final ZoneId systemDefault;
    public SignInTaskController(ISignInTaskService signInTaskService, ISysUserService sysUserService) {
        this.signInTaskService = signInTaskService;
        this.sysUserService = sysUserService;
        this.systemDefault = ZoneId.systemDefault();
    }

    /**
     * 查询任务列表
     */
    @SaCheckPermission("signIn:task:list")
    @GetMapping("/list")
    public TableDataInfo<SignInTaskVo> list(SignInTaskBo bo, PageQuery pageQuery) {
        return signInTaskService.queryPageList(bo, pageQuery);
    }

    @GetMapping("/listForUser")
    @SaCheckLogin
    public TableDataInfo<SignInTaskVo> listForUser(Long userId) {
        SysUserVo sysUserVo = sysUserService.selectUserById(userId);
        SignInTaskBo signInTaskBo = new SignInTaskBo();
        signInTaskBo.setDeptId(sysUserVo.getDeptId());

        List<SignInTaskVo> collect = signInTaskService.queryList(signInTaskBo)
            .stream()
            .filter(task -> {
                LocalDate now = LocalDate.now(systemDefault);
                LocalDate startDate = task.getStartTime().toInstant().atZone(systemDefault).toLocalDate();
                LocalDate endDate = task.getEndTime().toInstant().atZone(systemDefault).toLocalDate();
                return now.isAfter(startDate) && now.isBefore(endDate);
            })
            .collect(Collectors.toList());

        return TableDataInfo.build(collect);
    }

    /**
     * 导出任务列表
     */
    @SaCheckPermission("signIn:task:export")
    @Log(title = "任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SignInTaskBo bo, HttpServletResponse response) {
        List<SignInTaskVo> list = signInTaskService.queryList(bo);
        ExcelUtil.exportExcel(list, "任务", SignInTaskVo.class, response);
    }

    /**
     * 获取任务详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("signIn:task:query")
    @GetMapping("/{id}")
    public R<SignInTaskVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(signInTaskService.queryById(id));
    }

    /**
     * 新增任务
     */
    @SaCheckPermission("signIn:task:add")
    @Log(title = "任务", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SignInTaskBo bo) {
        validateTime(bo);
        return toAjax(signInTaskService.insertByBo(bo));
    }

    /**
     * 修改任务
     */
    @SaCheckPermission("signIn:task:edit")
    @Log(title = "任务", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SignInTaskBo bo) {
        validateTime(bo);
        return toAjax(signInTaskService.updateByBo(bo));
    }

    /**
     * 删除任务
     *
     * @param ids 主键串
     */
    @SaCheckPermission("signIn:task:remove")
    @Log(title = "任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(signInTaskService.deleteWithValidByIds(List.of(ids), true));
    }

    private void validateTime(SignInTaskBo bo) {
        ZonedDateTime startDateTime = bo.getStartTime().toInstant().atZone(systemDefault);
        ZonedDateTime endDateTime = bo.getEndTime().toInstant().atZone(systemDefault);

        LocalTime startTime = startDateTime.toLocalTime();
        LocalTime endTime = endDateTime.toLocalTime();
        if (startTime.isAfter(endTime)) {
            throw new RuntimeException("签到起始时间为"+startTime+",截止时间为"+endTime+"；截止时间不能早于起始时间");
        }
        if (startTime.equals(endTime)) {
            throw new RuntimeException("签到起始时间为"+startTime+",截止时间为"+endTime+"；起始时间不能等于截止时间");
        }
        LocalDate startDate = startDateTime.toLocalDate();
        LocalDate endDate = endDateTime.toLocalDate();
        if (startDate.isAfter(endDate)) {
            throw new RuntimeException("签到起始日期为"+startDate+",截止日期为"+endDate+"；截止日期不能早于起始日期");
        }
    }
}
